package org.example;

import bean.DB;
import bean.ResponseUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/DeleteCartItemServlet")
public class DeleteCartItemServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取 orderId 参数
        String orderIdStr = request.getParameter("orderId");

        if (orderIdStr == null || orderIdStr.isEmpty()) {
            // 调用 ResponseUtils 发送无效 ID 的提示信息
            ResponseUtils.sendResponse(response, "无效的商品编号", "cart.jsp");
            return;
        }

        int orderId;
        try {
            orderId = Integer.parseInt(orderIdStr);
        } catch (NumberFormatException e) {
            // 调用 ResponseUtils 发送无效 ID 的提示信息
            ResponseUtils.sendResponse(response, "无效的商品编号", "cart.jsp");
            return;
        }

        // 数据库删除操作
        String deleteQuery = "DELETE FROM usercart WHERE order_id = ?";
        DB db = new DB();

        try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(deleteQuery)) {
            pstmt.setInt(1, orderId);
            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                // 删除成功，调用 ResponseUtils 发送成功提示
                ResponseUtils.sendResponse(response, "商品删除成功！", "cart.jsp");
            } else {
                // 未找到该商品，调用 ResponseUtils 发送商品未找到的提示
                ResponseUtils.sendResponse(response, "未找到该商品", "cart.jsp");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            // 服务器错误，调用 ResponseUtils 发送错误提示
            ResponseUtils.sendResponse(response, "服务器错误，请稍后重试", "cart.jsp");
        }
    }
}
